using RabbitMQ.Client;

namespace Beauty.Net.RabbitMQ.WorkQueue
{
    /// <summary>
    /// 工作队列生产者
    /// </summary>
    public class WorkQueueProducer : RabbitMQProducerBase
    {
        public WorkQueueProducer(IRabbitMQConnectionManager connectionManager)
            : base(connectionManager)
        {}

        /// <summary>
        /// 发送任务到工作队列
        /// </summary>
        public void SendTask<T>(string queueName, T task, bool persistent = true)
        {
            using (var channel = _connectionManager.CreateChannel())
            {
                // 声明队列
                channel.QueueDeclare(queue: queueName,
                                    durable: persistent,
                                    exclusive: false,
                                    autoDelete: false,
                                    arguments: null);

                // 为了公平分发，设置预取计数为1
                channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                var properties = channel.CreateBasicProperties();
                properties.Persistent = persistent;

                var messageBody = System.Text.Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(task, _jsonOptions));
                channel.BasicPublish(exchange: string.Empty, routingKey: queueName, basicProperties: properties, body: messageBody);
            }
        }
    }
}